package com.yingxin.yxerp.module.dingtalk.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.TypeReference;
import com.yingxin.yx.framework.commons.constant.CommonConst;
import com.yingxin.yx.framework.commons.exception.BizException;
import com.yingxin.yxerp.module.dingtalk.config.WeComAppConfig;
import com.yingxin.yxerp.module.dingtalk.constant.WeComUrlConstant;
import com.yingxin.yxerp.module.dingtalk.dto.WeComDeptResultListDto;
import com.yingxin.yxerp.module.dingtalk.service.IWeComDeptBaseService;
import com.yingxin.yxerp.module.dingtalk.util.WeComAccessTokenUtil;
import com.yingxin.yxerp.module.dingtalk.vo.WeComDeptBaseRespVo;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;

import java.util.Arrays;
import java.util.List;

/**
 * 企业微信获取部门信息 实现类
 * yuebao
 * 24-09-23
 */

@Slf4j
@Service
public class WeComDeptBaseServiceImpl implements IWeComDeptBaseService {

    @Autowired
    private WeComAppConfig weComAppConfig;

    @Autowired
    private WeComAccessTokenUtil weComAccessTokenUtil;

    @Autowired
    private RestTemplate restTemplate;

    @Override
    public List<WeComDeptBaseRespVo> getDeptBaseList() {
        // 获取 AccessToken
        String accessToken = weComAccessTokenUtil.getAccessToken(
                weComAppConfig.getAppCorpId(), weComAppConfig.getAppSecret() );

        ResponseEntity<String> response = restTemplate.getForEntity(
                WeComUrlConstant.GET_DEPARTMENT_LIST_URL + "?access_token="+accessToken+"&id="+ CommonConst.TRUE,
                String.class );

        WeComDeptResultListDto dto = JSON.parseObject( response.getBody(), new TypeReference<WeComDeptResultListDto>(){} );

        if( dto.getErrcode().trim().equals( CommonConst.FALSE ) ){
            return Arrays.asList( dto.getDepartment() );
        }else{
            throw new BizException( dto.getErrmsg() );
        }
    }

}
